package com.zx.erp.market.controller;


import com.github.pagehelper.PageInfo;
import com.zx.erp.annonation.MyLog;
import com.zx.erp.market.bean.Custom;
import com.zx.erp.market.bean.Orderdetails;
import com.zx.erp.market.bean.Orders;
import com.zx.erp.market.service.CustomService;
import com.zx.erp.market.service.OrderdetailsService;
import com.zx.erp.market.service.OrdersService;
import com.zx.erp.purchase.bean.CBrand;
import com.zx.erp.purchase.bean.CProduct;
import com.zx.erp.purchase.bean.CType;
import com.zx.erp.purchase.service.CBrandService;
import com.zx.erp.purchase.service.CProductService;
import com.zx.erp.purchase.service.CTypeService;
import com.zx.erp.repo.bean.CkWarehouse;
import com.zx.erp.repo.bean.KcWarehouse;
import com.zx.erp.repo.bean.Warehouse;
import com.zx.erp.repo.service.CkWarehouseBiz;
import com.zx.erp.repo.service.KcWarehouseBiz;
import com.zx.erp.repo.service.WarehouseBiz;
import com.zx.erp.sys.bean.City;
import com.zx.erp.sys.bean.Province;
import com.zx.erp.sys.bean.Users;
import com.zx.erp.sys.service.CityService;
import com.zx.erp.sys.service.ProvinceService;
import com.zx.erp.sys.service.UsersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.sql.Date;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 作者信息
 * @since 2021-11-10
 */
@Controller
@RequestMapping("/market/order")
@SessionAttributes({"pb"})
public class OrdersController {
    @Autowired
    private OrdersService obiz;
    @Autowired
    private CustomService cbiz;
    @Autowired
    private UsersService ubiz;
    @Autowired
    private OrderdetailsService odbiz;
    @Autowired
    private CBrandService cbbiz;
    @Autowired
    private CTypeService ctbiz;
    @Autowired
    private CProductService cpbiz;
    @Autowired
    private WarehouseBiz wbiz;
    @Autowired
    private CkWarehouseBiz ckwbiz;
    @Autowired
    private ProvinceService probiz;
    @Autowired
    private CityService cityBiz;
    @Autowired
    private KcWarehouseBiz kcwbiz;


    //每次执行前会优先 将mid放入request范围
    @ModelAttribute
    public void initModuleData(HttpSession session) {
        session.removeAttribute("mid");
        session.setAttribute("mid", 8);
    }

    /**
     * 带条件的分页查询所有
     * @param orders
     * @param datemin 时间
     * @param datemax 时间
     * @param priceMin 金额
     * @param priceMax 金额
     * @param customname 客户姓名
     * @param pageNum 页码
     * @return
     */
    @RequestMapping("/findPageAll")
    @MyLog("订单分页模糊查询方法")
    public String findPageAll(Orders orders, String datemin, String datemax, Double priceMin, Double priceMax, String customname,
                              @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum, Model model) {
        List<Integer> cidList = new ArrayList<Integer>();
        if (customname != null && !customname.equals("")) {
            Custom custom = new Custom();
            custom.setCustomname(customname);
            List<Custom> customList = cbiz.findAll(custom);
            for (Custom c : customList) {
                cidList.add(c.getCustomid());
            }
        }
        Date dateMin = null;
        if (datemin != null && !datemin.equals("")) {
            dateMin = Date.valueOf(datemin);
        }
        Date dateMax = null;
        if (datemax != null && !datemax.equals("")) {
            dateMax = Date.valueOf(datemax);
        }
        PageInfo<Orders> pb = obiz.findPageAll(orders, cidList, dateMin, dateMax, priceMin, priceMax, pageNum, 6);
        model.addAttribute("pb", pb);
        model.addAttribute("customname", customname);
        model.addAttribute("orders", orders);
        model.addAttribute("dateMin", dateMin);
        model.addAttribute("dateMax", dateMax);
        model.addAttribute("priceMin", priceMin);
        model.addAttribute("priceMax", priceMax);

        Users user = new Users();
        user.setJobId(2);
        user.setStatusId(1);
        List<Users> userList = ubiz.findAll(user);
        model.addAttribute("userList", userList);
        return "forward:/market/order/orderList.html";
    }

    /**
     * 客户销售统计
     * @param customname 客户姓名
     * @param pid  省id
     * @param address 市id
     * @param pageNum 页码
     * @return
     */
    @RequestMapping("/findPageAllFZ")
    @MyLog("客户销售统计")
    public String findPageAllFZ(String customname,Integer pid,Integer address, Model model,
                                @RequestParam(value = "pageNum", defaultValue = "1")Integer pageNum){
        List<Integer> cidList1=new ArrayList<Integer>();
        List<Integer> cidList2=new ArrayList<Integer>();
        List<Integer> cList=new ArrayList<Integer>();
        if(address==null || address==0){
            if(pid!=null && pid !=0){
                List<City> byPid = cityBiz.findByPid(pid);
                for (City c:byPid){
                    cList.add(c.getId());
                }
                List<Custom> customs = cbiz.findByAddress(cList);
                if(customs.size()==0){
                    cidList1.add(0);
                }
                for (Custom c:customs){
                    cidList1.add(c.getCustomid());
                }
            }
        }else{
            cList.add(address);
            List<Custom> customs = cbiz.findByAddress(cList);
            if(customs.size()==0){
                cidList1.add(0);
            }
            for (Custom c:customs){
                cidList1.add(c.getCustomid());
            }
            model.addAttribute("cid",address);
        }

        if(customname!=null && !customname.equals("")){
            Custom custom=new Custom();
            custom.setCustomname(customname);
            List<Custom> customs = cbiz.findAll(custom);
            if(customs.size()==0){
                cidList2.add(0);
            }
            for (Custom c:customs){
                cidList2.add(c.getCustomid());
            }
        }


        PageInfo<Orders> pb = obiz.findAllFZ(cidList1,cidList2, null, null, pageNum, 6);
        model.addAttribute("pb",pb);
        model.addAttribute("pid",pid);
        List<Province> provinceList = probiz.findAll();
        model.addAttribute("provinceList", provinceList);
        model.addAttribute("customname",customname);

        return "forward:/statis/sales/salesStatis.html";
    }


    /**
     * 客户销售统计  统计图一层
     * @param customname
     * @param pid
     * @param address
     * @param pageNum
     * @return
     */
    @RequestMapping("ajaxFindPageAllFZ")
    @ResponseBody
    public List<Orders> ajaxFindPageAllFZ(String customname,Integer pid,Integer address,
                                          @RequestParam(value = "pageNum", defaultValue = "1")Integer pageNum){
        List<Integer> cidList1=new ArrayList<Integer>();
        List<Integer> cidList2=new ArrayList<Integer>();
        List<Integer> cList=new ArrayList<Integer>();
        if(address==null || address==0){
            if(pid!=null && pid !=0){
                List<City> byPid = cityBiz.findByPid(pid);
                for (City c:byPid){
                    cList.add(c.getId());
                }
                List<Custom> customs = cbiz.findByAddress(cList);
                if(customs.size()==0){
                    cidList1.add(0);
                }
                for (Custom c:customs){
                    cidList1.add(c.getCustomid());
                }
            }
        }else{
            cList.add(address);
            List<Custom> customs = cbiz.findByAddress(cList);
            if(customs.size()==0){
                cidList1.add(0);
            }
            for (Custom c:customs){
                cidList1.add(c.getCustomid());
            }
        }

        if(customname!=null && !customname.equals("")){
            Custom custom=new Custom();
            custom.setCustomname(customname);
            List<Custom> customs = cbiz.findAll(custom);
            if(customs.size()==0){
                cidList2.add(0);
            }
            for (Custom c:customs){
                cidList2.add(c.getCustomid());
            }
        }

        List<Orders> list = obiz.findAllFZ(cidList1, cidList2, null, null, pageNum, 6).getList();
        return list;
    }


    /**
     * 客户销售统计的查看详情
     * @param customid 客户id
     * @param pageNum 页码
     * @return
     */
    @RequestMapping("/findBydDelivery")
    @MyLog("客户销售统计的查看详情")
    public String findByCKWarehouse(Integer customid,Model model,
                                    @RequestParam(value = "pageNum", defaultValue = "1")Integer pageNum){
        PageInfo<Orderdetails> odpb = odbiz.findAllFZ(customid, pageNum, 6);
        model.addAttribute("odpb",odpb);
        model.addAttribute("customid",customid);
        return "forward:/statis/sales/salesView.html";
    }

    /**
     * 客户销售统计  统计图二层
     * @param pageNum
     * @return
     */
    @RequestMapping("/ajaxFindByCKWarehouse")
    @ResponseBody
    public List<List<Orderdetails>> ajaxFindByCKWarehouse(@RequestParam(value = "pageNum", defaultValue = "1")Integer pageNum){
        List<Orders> listP = obiz.findAllFZ(null, null, null, null, pageNum, 6).getList();
        List<List<Orderdetails>> listC=new ArrayList<List<Orderdetails>>();
        for (Orders o:listP){
            List<Orderdetails> list = odbiz.findAllFZ(o.getCustomid(), 1, 999999999).getList();
            listC.add(list);
        }
        return listC;
    }


    /**
     * 提交审核
     * @param orderid 订单id
     * @param uid  用户id
     * @return
     */
    @RequestMapping("/editStatus")
    @MyLog("提交审核")
    public String editStatus(String orderid,Integer uid,Model model) {
        boolean flag = obiz.editStatus(orderid,uid);
        PageInfo<Orders> pb = (PageInfo<Orders>) model.getAttribute("pb");
        Integer pageNum=pb.getPageNum();
        if (flag){
            return "redirect:/market/order/findPageAll?pageNum="+pageNum;
        }else{
            return "";
        }
    }

    /**
     * 订单详情
     * @param orderid 订单id
     * @return
     */
    @RequestMapping("/findByDetails")
    @MyLog("订单详情")
    public String findByDetails(String orderid, Model model){
        List<Orderdetails> orderdetails = odbiz.findByOrderId(orderid);
        Orders order1 = obiz.findBy(orderid);
        model.addAttribute("orderDs",orderdetails);
        model.addAttribute("order1",order1);
        return "forward:/market/order/orderView.html";
    }

    /**
     * 查询所有品牌
     * @return
     */
    @RequestMapping("/ajaxBrandAll")
    @ResponseBody
    public List<CBrand> ajaxBrandAll(){
        CBrand cBrand=new CBrand();
        cBrand.setBrandStatus(1);
        PageInfo<CBrand> pb = cbbiz.findAll(cBrand, 1, 99999);
        return pb.getList();
    }

    /**
     * 通过品牌id查类型
     * @param brandId
     * @return
     */
    @RequestMapping("/ajaxTypeByBrandId")
    @ResponseBody
    public List<CType> ajaxTypeByBrandId(Integer brandId){
        List<CType> cTypes = ctbiz.findbyBrandId(brandId);
        return cTypes;
    }


    /**
     * 通过类型id查商品
     * @param typeId
     * @return
     */
    @RequestMapping("/ajaxProductTypeId")
    @ResponseBody
    public List<CProduct> ajaxProductTypeId(Integer typeId){
        List<CProduct> cProducts = cpbiz.findbyTypeId(typeId);
        return cProducts;
    }

    /**
     * 查询 uid用户下的所有客户
     * @param uid
     * @return
     */
    @RequestMapping("/ajaxCustomAll")
    @ResponseBody
    public List<Custom> ajaxCustomAll(Integer uid,HttpSession session){
        Users users = (Users) session.getAttribute("users");
        Custom custom = new Custom();
        if (users.getJobId()!=1){
            custom.setServiceid(uid);
        }
        custom.setStatus(1);
        List<Custom> customs = cbiz.findAll(custom);
        return customs;
    }

    /**
     * 查询能给orderid订单提供商品的仓库
     * @param orderid
     * @return
     */
    @RequestMapping("/ajaxWarehouseAll")
    @ResponseBody
    public List<Warehouse> ajaxWarehouseAll(String orderid){
        List<Orderdetails> orderDs = this.odbiz.findByOrderId(orderid);
        Set<Integer> integerSet=new HashSet<Integer>();
        for (Orderdetails od:orderDs){
            KcWarehouse kcw=new KcWarehouse();
            kcw.setBrandId(od.getProduct().getBrandId());
            kcw.setTypeId(od.getProduct().getTypeId());
            kcw.setFactoryId(od.getProduct().getFirmId());
            kcw.setProductId(od.getProductId());
            kcw.setRepertory(od.getPurchaseNum());
            List<KcWarehouse> by5c = kcwbiz.findBy5c(kcw);
            for (KcWarehouse kc:by5c){
                integerSet.add(kc.getWarehouseId());
            }
        }
        List<Warehouse> warehouses=new ArrayList<Warehouse>();
        for (Integer i:integerSet){
            warehouses.add(wbiz.findWareById(i));
        }
        return warehouses;
    }

    /**
     * 添加订单
     * @param orders
     * @return
     */
    @RequestMapping("/addOrders")
    @MyLog("添加订单")
    public String addOrders(Orders orders, HttpServletRequest request){
        orders.setOrdertime(new Date(System.currentTimeMillis()));
        List<Orderdetails> oDerdetas=new ArrayList<Orderdetails>();
        String[] productIds = request.getParameterValues("productId");
        String[] purchaseNums = request.getParameterValues("purchaseNum");
        String[] proprices = request.getParameterValues("proprice");
        String[] prototals = request.getParameterValues("prototal");
        if (productIds==null){
            return "forward:/market/order/orderAdd.html";
        }
        for (int i=0;i<productIds.length;i++){
            if(productIds[i]!=null && !productIds[i].equals("0") && !productIds[i].equals("") ||
                    purchaseNums[i]!=null && !purchaseNums[i].equals("") && !purchaseNums[i].equals("0") ||
                    proprices[i]!=null && !proprices[i].equals("") && !proprices[i].equals("0") ||
                    prototals[i]!=null && !prototals[i].equals("0") && !prototals[i].equals("")) {
                Orderdetails oDerdeta=new Orderdetails();
                oDerdeta.setProductId(Integer.parseInt(productIds[i]));
                oDerdeta.setPurchaseNum(Integer.parseInt(purchaseNums[i]));
                oDerdeta.setProprice(Integer.parseInt(proprices[i]));
                oDerdeta.setPrototal(Integer.parseInt(prototals[i]));
                oDerdetas.add(oDerdeta);
            }else{
                return "forward:/market/order/orderAdd.html";
            }
        }
        boolean flag = obiz.addOrders(orders, oDerdetas);
        if (flag){
            return "redirect:/market/order/findPageAll?pageNum=1";
        }else{
            return "";
        }
    }

    /**
     * 跳转到修改订单页面
     * @param orderid
     * @return
     */
    @RequestMapping("/goEditOrders")
    public String goEditOrders(String orderid, Model model, HttpSession session){
        Orders order = obiz.findBy(orderid);
        Users users = (Users) session.getAttribute("users");
        Custom custom = new Custom();
        if (users.getJobId()!=1){
            custom.setServiceid(users.getUId());
        }
        List<Custom> customs = cbiz.findAll(custom);
        List<Orderdetails> oDerdetas = odbiz.findByOrderId(orderid);
        List<CBrand> brands = cbbiz.findAll(new CBrand(), 1, 99998999).getList();
        List<CType> types = ctbiz.findAll(new CType(), 1, 99999999).getList();
        List<CProduct> products = cpbiz.findAll(new CProduct(), 1, 99999999).getList();
        model.addAttribute("order",order);
        model.addAttribute("brands",brands);
        model.addAttribute("types",types);
        model.addAttribute("products",products);
        model.addAttribute("customs",customs);
        model.addAttribute("orderDs",oDerdetas);
        return"forward:/market/order/orderUpdate.html";
    }

    /**
     * 修改订单
     * @param orders
     * @return
     */
    @RequestMapping("/editOrders")
    @MyLog("修改订单")
    public String editOrders(Orders orders, HttpServletRequest request,Model model){
        List<Orderdetails> oDerdetas=new ArrayList<Orderdetails>();
        String[] productIds = request.getParameterValues("productId");
        String[] purchaseNums = request.getParameterValues("purchaseNum");
        String[] proprices = request.getParameterValues("proprice");
        String[] prototals = request.getParameterValues("prototal");
        if (productIds==null){
            return "forward:/market/order/orderAdd.html";
        }
        for (int i=0;i<productIds.length;i++){
            if(productIds[i]!=null && !productIds[i].equals("0") && !productIds[i].equals("") ||
                    purchaseNums[i]!=null && !purchaseNums[i].equals("") && !purchaseNums[i].equals("0") ||
                    proprices[i]!=null && !proprices[i].equals("") && !proprices[i].equals("0") ||
                    prototals[i]!=null && !prototals[i].equals("0") && !prototals[i].equals("")) {
                Orderdetails oDerdeta = new Orderdetails();
                oDerdeta.setProductId(Integer.parseInt(productIds[i]));
                oDerdeta.setPurchaseNum(Integer.parseInt(purchaseNums[i]));
                oDerdeta.setProprice(Integer.parseInt(proprices[i]));
                oDerdeta.setPrototal(Integer.parseInt(prototals[i]));
                oDerdeta.setOrderId(orders.getOrderid());
                oDerdetas.add(oDerdeta);
            }
        }
        boolean flag = obiz.editOrdersAndOrderDS(orders, oDerdetas);
        PageInfo<Orders> pb = (PageInfo<Orders>) model.getAttribute("pb");
        Integer pageNum=pb.getPageNum();
        if(flag){
            return "redirect:/market/order/findPageAll?pageNum="+pageNum;
        }else{
            return "";
        }
    }


    /**
     * 出库详情
     * @param orderid
     * @return
     */
    @RequestMapping("/outWarehouseBy")
    @MyLog("出库详情")
    public String outWarehouseBy(String orderid,Model model){
        Orders order = obiz.findBy(orderid);
        model.addAttribute("order",order);
        List<Orderdetails> orderDs = this.odbiz.findByOrderId(orderid);
        model.addAttribute("orderDs",orderDs);
        CkWarehouse ckw=new CkWarehouse();
        ckw.setWarehouseId(order.getWarehouseId());
        ckw.setIndent(orderid);
        List<CkWarehouse> list = ckwbiz.findAllCk(null, ckw, 1, 999999999).getList();
        CkWarehouse ckWarehouse=null;
        if(list.size()!=0){
            ckWarehouse= list.get(0);
        }
        model.addAttribute("ckws",ckWarehouse);
        return "forward:/storage/delivery/deliveryView.html";
    }

    /**
     * 删除订单
     * @param orderid
     * @return
     */
    @RequestMapping("/delOrders")
    @MyLog("删除订单")
    public String delOrders(String orderid,Model model){
        boolean flag = obiz.delOrders(orderid);
        PageInfo<Orders> pb = (PageInfo<Orders>) model.getAttribute("pb");
        Integer pageNum=pb.getPageNum();
        if (pageNum==pb.getPages()){
            if(pb.getTotal()%pb.getPageSize()==1){
                pageNum-=1;
            }
        }
        if(flag){
            return "redirect:/market/order/findPageAll?pageNum="+pageNum;
        }else{
            return "";
        }
    }

    /**
     * 查询不在出库表中的订单   状态是审核通过
     * @return
     */
    @RequestMapping("/ajaxOrderStatus3")
    @ResponseBody
    public List<Orders> ajaxOrderStatus3(){
        List<Orders> orders = obiz.findNotCkWOrderid();
        return orders;
    }
}


